package com.example.ivideo_2211a.fabu

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

import com.example.common.mvi.MviViewState

sealed class CreateViewState : MviViewState {
    object Idle : CreateViewState()
    object Loading : CreateViewState()
    data class Success(val msg: String) : CreateViewState()
    data class Error(val error: String) : CreateViewState()
}

class CreateViewModel : BaseViewModel<CreateIntent, CreateViewState, Nothing>() {
    override fun initialState(): CreateViewState = CreateViewState.Idle

    override suspend fun handleIntent(intent: CreateIntent) {
        when (intent) {
            is CreateIntent.PublishVideo -> publishVideo(intent.json)
        }
    }

    private fun publishVideo(json: JSONObject) {
        updateState(CreateViewState.Loading)
        viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val body = json.toString().toRequestBody("application/json".toMediaTypeOrNull())
                val request = Request.Builder()
                    .url("http://10.161.9.80:7015/api/videos/publish")
                    .post(body)
                    .build()
                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    // 回到主线程更新UI
                    kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                        updateState(CreateViewState.Success("发布成功"))
                    }
                } else {
                    kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                        updateState(CreateViewState.Error("发布失败：${response.code}"))
                    }
                }
            } catch (e: Exception) {
                val stack = e.stackTraceToString()
                val msg = "${e.javaClass.simpleName}: ${e.message}\n$stack"
                kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                    updateState(CreateViewState.Error("网络异常：$msg"))
                }
            }
        }
    }
}
